package com.ljfiction.book.activitys;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.Hotwords;
import com.ljfiction.book.MyView.DBHelper;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.MyView.FlowLayout;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.HistorySearchAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.tools.StringTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class SearchActivity extends BaseActivity {

    @BindView(R.id.back_searchactivity)
    ImageView backSearchactivity;

    @BindView(R.id.search_search)
    TextView searchSearch;
    @BindView(R.id.flowlayout_search)
    FlowLayout flowlayoutSearch;
    @BindView(R.id.recycleview_search)
    RecyclerView recycleviewSearch;
    @BindView(R.id.searchtext_search)
    SearchView searchtextSearch;
    private Hotwords hotwords;
    private List<Hotwords.DataBean> listHotwors = new ArrayList<>();
    private DBHelper dbHelper;
    private HistorySearchAdapter adapterre;
    private List<String> listString = new ArrayList<>();
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        dbHelper = new DBHelper(this);
        intent = new Intent(SearchActivity.this, SearchOkActivity.class);
        toSearchview();
        searchtextSearch.onActionViewExpanded();
        searchtextSearch.clearFocus();
        intData();
        intRecycleData();
    }

    private void intRecycleData() {
        listString = dbHelper.getAllHistory();
        adapterre = new HistorySearchAdapter(R.layout.hitorysearchitem, listString);
        recycleviewSearch.setAdapter(adapterre);
        recycleviewSearch.setLayoutManager(new LinearLayoutManager(this));
        recycleviewSearch.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        adapterre.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intent.putExtra("searchtext", listString.get(position));
                startActivity(intent);

            }
        });
        adapterre.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                dbHelper.deleteHistory(listString.get(position).toString());
                listString.clear();
                listString.addAll(dbHelper.getAllHistory());
                adapterre.notifyDataSetChanged();
            }
        });
    }

    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/sys-hotwords")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        Gson gson = new Gson();
                        hotwords = gson.fromJson(s, Hotwords.class);
                        if (hotwords.getReturnCode() == 200) {
                            listHotwors = hotwords.getData();
                            tointFlowlayout();
                        }

                    }
                });
    }

    private void tointFlowlayout() {
        for (int i = 0; i < listHotwors.size(); i++) {
            if (StringTool.isEmpty(listHotwors.get(i).getHotWords())){
                continue;
            }
            final SuperButton txt = (SuperButton) getLayoutInflater().inflate(R.layout.flowtextview, flowlayoutSearch, false);
            txt.setText(listHotwors.get(i).getHotWords());
            txt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intent.putExtra("searchtext", txt.getText().toString());
                    startActivity(intent);
                }
            });
            flowlayoutSearch.addView(txt);
        }
    }

    @OnClick({R.id.back_searchactivity, R.id.search_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_searchactivity:
                goBack();
                break;
            case R.id.search_search:
                if (StringTool.isEmpty(searchtextSearch.getQuery().toString())) {
                    showToast("搜索内容不能为空");
                    return;
                }
                intent.putExtra("searchtext", searchtextSearch.getQuery().toString());
                dbHelper.insertHistory(searchtextSearch.getQuery().toString());
                listString.clear();
                listString.addAll(dbHelper.getAllHistory());
                adapterre.notifyDataSetChanged();
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        searchtextSearch.setFocusable(true);
        searchtextSearch.setFocusableInTouchMode(true);
        searchtextSearch.requestFocus();
        if (dbHelper!=null&&adapterre!=null){
            listString.clear();
            listString.addAll(dbHelper.getAllHistory());
            adapterre.notifyDataSetChanged();
        }
    }
    private void toSearchview() {
        searchtextSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (StringTool.isEmpty(searchtextSearch.getQuery().toString())) {
                    showToast("搜索内容不能为空");
                    return false;
                }
                intent.putExtra("searchtext", searchtextSearch.getQuery().toString());
                dbHelper.insertHistory(searchtextSearch.getQuery().toString());
                listString.clear();
                listString.addAll(dbHelper.getAllHistory());
                adapterre.notifyDataSetChanged();
                startActivity(intent);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        if (searchtextSearch != null) {
            SearchView.SearchAutoComplete textView = (SearchView.SearchAutoComplete) searchtextSearch.findViewById(R.id.search_src_text);
            textView.setTextColor(Color.parseColor("#666666"));//字体颜色
            textView.setTextSize(12);//字体、提示字体大小
            textView.setHintTextColor(Color.parseColor("#999999"));//提示字体颜色
            try {        //--拿到字节码
                Class<?> argClass = searchtextSearch.getClass();
                //--指定某个私有属性,mSearchPlate是搜索框父布局的名字
                Field ownField = argClass.getDeclaredField("mSearchPlate");
                //--暴力反射,只有暴力反射才能拿到私有属性
                ownField.setAccessible(true);
                View mView = (View) ownField.get(searchtextSearch);
                //--设置背景
                mView.setBackgroundResource(R.drawable.search_shaoer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
